﻿/************************************************************************

 This file is part of "10 Second Tim".

 "10 Second Tim" is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 "10 Second Tim" is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with "10 Second Tim".  If not, see <http://www.gnu.org/licenses/>.

************************************************************************/

// All code (c)2013 Scott Bevin. all rights reserved

using Microsoft.Xna.Framework;

namespace LDE
{
	public class Camera
	{
		private Vector2 halfScreenDim = Vector2.Zero;

		public Vector2 TargetPosition = Vector2.Zero;
		public Vector2 Position = Vector2.Zero;

		public float Zoom = 0.55f;
		public float Rotation = 0.0f;
		public float TargetRotation = 0.0f;

		public Camera( int screenWidth, int screenHeight )
		{
			halfScreenDim = new Vector2( (float)( screenWidth ), (float)( screenHeight ) );
			halfScreenDim *= 0.5f;
		}

		public void Update( float dt )
		{
			Vector2 offset = TargetPosition - Position;
			Position += ( offset * dt * 10.0f );

			float roffset = TargetRotation - Rotation;
			Rotation += ( roffset * dt );
#if DEBUG
			DebugDraw.Get.AddText( "Camera - Pos: " + Position.ToString( ) + " Targ: " + TargetPosition.ToString( ) + "Zoom: " + Zoom );
#endif
		}

		public Matrix GetWorldMatrix( )
		{
			return Matrix.CreateTranslation( new Vector3( -Position.X, -Position.Y, 0.0f ) ) *
				Matrix.CreateRotationZ( Rotation ) *
				Matrix.CreateScale( new Vector3( Zoom, Zoom, 1.0f ) ) *
				Matrix.CreateTranslation( halfScreenDim.X, halfScreenDim.Y, 0.0f );
		}

		public Vector2 ScreenToWorld( Vector2 pos )
		{
			Matrix mtx = GetWorldMatrix( );
			mtx = Matrix.Invert( mtx );
			return Vector2.Transform( pos, mtx );
		}

		public bool ClipTest( Vector2 pos, float radius )
		{
			bool outOfView =
				( pos.X + radius < Position.X - halfScreenDim.X ) ||
				( pos.X - radius > Position.X - halfScreenDim.X ) ||
				( pos.Y + radius < Position.Y - halfScreenDim.Y ) ||
				( pos.Y - radius > Position.Y - halfScreenDim.Y );

			return !outOfView;
		}
	}
}